package com.onluy.frameworkcloud.tools;

 
import java.security.Key;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import com.onluy.frameworkcloud.tools.utils.StringUtil;

public class CipherManage {
	private static Map<String, Cipher> encryptMap = new ConcurrentHashMap();
	private static ReentrantReadWriteLock encrypLock = new ReentrantReadWriteLock();
	private static Map<String, Cipher> decryptMap = new ConcurrentHashMap();
	private static ReentrantReadWriteLock decryptLock = new ReentrantReadWriteLock();

	public static ReentrantReadWriteLock getEncrypLock() {
		return encrypLock;
	}

	public static ReentrantReadWriteLock getDecryptLock() {
		return decryptLock;
	}

	public static Cipher getEncrypt(String keyValue) throws Exception {
		if (StringUtil.isEmpty(keyValue)) {
			throw new Exception("未传入加密密钥");
		} else {
			if (!encryptMap.containsKey(keyValue)) {
				encrypLock.writeLock().lock();

				try {
					if (!encryptMap.containsKey(keyValue)) {
						Key e = getKey(keyValue.getBytes());
						Cipher encrypt = Cipher.getInstance("DES");
						encrypt.init(1, e);
						encryptMap.put(keyValue, encrypt);
					}
				} catch (Exception arg5) {
					throw new Exception("加密秘钥：" + keyValue + "加密失败:" + arg5.getMessage());
				} finally {
					encrypLock.writeLock().unlock();
				}
			}

			return (Cipher) encryptMap.get(keyValue);
		}
	}

	public static Cipher getDecrypt(String keyValue) throws Exception {
		if (StringUtil.isEmpty(keyValue)) {
			throw new Exception("未传入加密密钥");
		} else {
			if (!decryptMap.containsKey(keyValue)) {
				decryptLock.writeLock().lock();

				try {
					if (!decryptMap.containsKey(keyValue)) {
						Key e = getKey(keyValue.getBytes());
						Cipher decrypt = Cipher.getInstance("DES");
						decrypt.init(2, e);
						decryptMap.put(keyValue, decrypt);
					}
				} catch (Exception arg5) {
					throw new Exception("加密秘钥：" + keyValue + "解密失败:" + arg5.getMessage());
				} finally {
					decryptLock.writeLock().unlock();
				}
			}

			return (Cipher) decryptMap.get(keyValue);
		}
	}

	public static void removeDecrypt(String keyValue) {
		decryptMap.remove(keyValue);
	}

	public static void removeEncrypt(String keyValue) {
		encryptMap.remove(keyValue);
	}

	private static Key getKey(byte[] arrBTmp) throws Exception {
		byte[] arrB = new byte[8];

		for (int key = 0; key < arrBTmp.length && key < arrB.length; ++key) {
			arrB[key] = arrBTmp[key];
		}

		SecretKeySpec arg2 = new SecretKeySpec(arrB, "DES");
		return arg2;
	}
}